<?php

namespace app\admin\controller;


use think\Cache;

class Information extends BaseController {
    public function _initialize() {
        $timeLine = Cache::get('timeLine');
        if ($timeLine) {
            return;
        }
        $condition['is_top'] = 1;
        $condition['status'] = ['neq', config('code.status_delete')];
        $infos               = model('Information')
            ->field('id,is_top,top_expert,status')
            ->where($condition)
            ->select();
        if ($infos) {
            foreach ($infos as $info) {
                if (time() > $info->top_expert) {
                    $info->is_top = 0;
                    $info->save();
                }
            }
        }
        Cache::set('timeLine', '2个小时', config('setting.token_expire_in'));
    }

    public function index() {
        $query = input('get.');
        if (!empty($query['parent_id'])) {
            $condition = model('Category')->getCatCondition($query['parent_id']);
        }
        if (!empty($query['start']) && !empty($query['end'])) {
            $condition['create_time'] = ['between', [$query['start'], $query['end']]];
        }
    }

    public function read($id) {
        $result = model('Information')->get($id);
        if (!$result) {
            return show(config('code.fail'), '获取数据失败');
        }
        return show(config('code.success'), '获取数据成功', $result);
    }

    public function update($id) {
        $date = input('put.date');
        if (isset($date)) {
            $topExpert = time() + $date * 24 * 60 * 60;
            $result    = model('Information')->where(['id' => $id])->update([
                'top_expert' => $date != 0 ? $topExpert : 0,
                'is_top'     => $date != 0 ? 1 : 0
            ]);
            if (!$result) {
                return show(config('code.fail'), '设置置顶失败');
            }
            return show(config('code.success'), '设置置顶成功');
        }
        $catId = input('put.cat_id');
        if (isset($catId)) {
            $result = model('Information')->where(['id' => $id])->update([
                'cat_id' => $catId
            ]);
            if (!$result) {
                return show(config('code.fail'), '修改分类失败');
            }
            return show(config('code.success'), '修改分类成功');
        }
        return show(config('code.fail'), '参数错误');
    }

    public function save() {
        $data = input('post.');
        if (empty($data['id'])) {
            $id = model('Information')->add($data);
        } else {
            $id = model('Information')->edit($data, $data['id']);
        }

        if (!$id) {
            return show(config('code.fail'), '添加资讯错误');
        }
        return show(config('code.success'), '添加资讯成功');
    }
}